package org.jeecg.modules.sistersophie.controller;

import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lowagie.text.DocumentException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.config.StaticConfig;
import org.jeecg.modules.sistersophie.constans.GlobalConstans;
import org.jeecg.modules.sistersophie.entity.InvoiceInfo;
import org.jeecg.modules.sistersophie.facade.InvoiceFacade;
import org.jeecg.modules.sistersophie.model.request.InvoiceAddRequest;
import org.jeecg.modules.sistersophie.model.request.InvoicePaymentCompletedRequest;
import org.jeecg.modules.sistersophie.service.IInvoiceInfoService;
import org.jeecg.modules.sistersophie.view.InvoicePdfView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

/**
 * @Description: invoice_info
 * @Author: jeecg-boot
 * @Date:   2021-06-04
 * @Version: V1.0
 */
@Api(tags="invoice_info")
@RestController
@RequestMapping("/sistersophie/invoiceInfo")
@Slf4j
public class InvoiceInfoController extends JeecgController<InvoiceInfo, IInvoiceInfoService> {
	@Autowired
	private IInvoiceInfoService invoiceInfoService;

	@Autowired
	private InvoiceFacade invoiceFacade;

	@Autowired
	private StaticConfig staticConfig;
	
	/**
	 * 分页列表查询
	 *
	 * @param invoiceInfo
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "invoice_info-分页列表查询")
	@ApiOperation(value="invoice_info-分页列表查询", notes="invoice_info-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(InvoiceInfo invoiceInfo,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<InvoiceInfo> queryWrapper = QueryGenerator.initQueryWrapper(invoiceInfo, req.getParameterMap());
		Page<InvoiceInfo> page = new Page<InvoiceInfo>(pageNo, pageSize);
		IPage<InvoiceInfo> pageList = invoiceFacade.pageList(invoiceInfo, pageNo,pageSize,req);
		if(pageList != null && pageList.getRecords() != null && pageList.getRecords().size() > 0){
			for(InvoiceInfo info : pageList.getRecords()){
				if(info.getAmount() != null){
					info.setAmountFormat(GlobalConstans.CURRENCY + NumberUtil.decimalFormat(GlobalConstans.DECIMARPATTERN,info.getAmount()));
				}
				if(info.getInvoiceAmount() != null){
					info.setInvoiceAmountFormat(GlobalConstans.CURRENCY + NumberUtil.decimalFormat(GlobalConstans.DECIMARPATTERN,info.getInvoiceAmount()));
				}
			}
		}
		return Result.OK(pageList);
	}

	/**
	 *   添加
	 *
	 * @param addRequest
	 * @return
	 */
	 @AutoLog(value = "invoice_info-添加")
	 @ApiOperation(value="invoice_info-添加", notes="invoice_info-添加")
	 @PostMapping(value = "/add")
	 public Result<?> add(@RequestBody InvoiceAddRequest addRequest) {
		 invoiceFacade.addInvoice(addRequest);
		 return Result.OK("Added successfully！");
	 }


	 @AutoLog(value = "paymentCompleted")
	 @ApiOperation(value="paymentCompleted", notes="paymentCompleted")
	 @PostMapping(value = "/paymentCompleted")
	 public Result<?> paymentCompleted(@RequestBody InvoicePaymentCompletedRequest request) {
		 invoiceFacade.paymentCompleted(request);
		 return Result.OK("successfully！");
	 }

	/*@AutoLog(value = "invoice_info-添加")
	@ApiOperation(value="invoice_info-添加", notes="invoice_info-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody InvoiceInfo invoiceInfo) {
		invoiceInfoService.save(invoiceInfo);
		return Result.OK("添加成功！");
	}*/
	
	/**
	 *  编辑
	 *
	 * @param request
	 * @return
	 */
	@AutoLog(value = "invoice_info-编辑")
	@ApiOperation(value="invoice_info-编辑", notes="invoice_info-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody InvoiceAddRequest request) {
		invoiceFacade.updateInvoice(request);
		return Result.OK("Edit successfully!");
	}

	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "invoice_info-通过id删除")
	@ApiOperation(value="invoice_info-通过id删除", notes="invoice_info-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		invoiceFacade.deleteInvoice(id);
		return Result.OK("Successfully deleted!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "invoice_info-批量删除")
	@ApiOperation(value="invoice_info-批量删除", notes="invoice_info-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.invoiceInfoService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "invoice_info-通过id查询")
	@ApiOperation(value="invoice_info-通过id查询", notes="invoice_info-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		InvoiceInfo invoiceInfo = invoiceInfoService.getById(id);
		if(invoiceInfo==null) {
			return Result.error("未找到对应数据");
		}else{
			if(invoiceInfo.getInvoiceAmount() != null){
				invoiceInfo.setInvoiceAmountFormat(GlobalConstans.CURRENCY + NumberUtil.decimalFormat(GlobalConstans.DECIMARPATTERN,invoiceInfo.getInvoiceAmount()));
			}
			if(invoiceInfo.getAmount() != null){
				invoiceInfo.setAmountFormat(GlobalConstans.CURRENCY + NumberUtil.decimalFormat(GlobalConstans.DECIMARPATTERN,invoiceInfo.getAmount()));
			}

			if(invoiceInfo.getDiscountAmount() != null){
				invoiceInfo.setDiscountAmountFormat(GlobalConstans.CURRENCY + NumberUtil.decimalFormat(GlobalConstans.DECIMARPATTERN,invoiceInfo.getDiscountAmount()));
			}

			if(invoiceInfo.getTaxAfterAmount() != null){
				invoiceInfo.setTaxAfterAmountFormat(GlobalConstans.CURRENCY + NumberUtil.decimalFormat(GlobalConstans.DECIMARPATTERN,invoiceInfo.getTaxAfterAmount()));
			}
		}
		return Result.OK(invoiceInfo);
	}

	 @AutoLog(value = "downloadPdf")
	 @ApiOperation(value="downloadPdf", notes="downloadPdf")
	 @GetMapping(value = "/downloadPdf")
	 public ModelAndView downloadPdf(@RequestParam(name="id",required=true) String id,
								  HttpServletRequest req,
								  HttpServletResponse response) {

		 ModelAndView mv = new ModelAndView(new InvoicePdfView());
		 try {
			 invoiceFacade.downLoadPdf(mv,id);
		 } catch (Exception e) {
			 e.printStackTrace();
		 }
		 return mv;
	 }

	@GetMapping(value = "/preview/pdf/{id}")
	public ModelAndView previewPdf(@PathVariable("id") String id,
									HttpServletRequest req,
									HttpServletResponse response) {
		ModelAndView mv = new ModelAndView(new InvoicePdfView());
		try {
			mv.getModel().put("serverPath",staticConfig.getServerPath());
			invoiceFacade.downLoadPdf(mv,id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mv;
	}

	 @AutoLog(value = "sendEmail")
	 @ApiOperation(value="sendEmail", notes="sendEmail")
	 @GetMapping(value = "/sendEmail")
	 public Result<?> sendEmail(@RequestParam(name="id",required=true) String id,
								@RequestParam(name="paymentMethod",required=true) String paymentMethod) {
		 try {
			 invoiceFacade.sendEmail(id,paymentMethod);
			 return Result.OK("Email sent Successfully ");
		 } catch (Exception e) {
			 e.printStackTrace();
			 return Result.OK("Email sending failed");
		 }
	 }



	 @GetMapping(value = "/pdf")
	 public Result<?> pdf() {
		 try {
			 invoiceFacade.generatePdfFile();
		 } catch (IOException e) {
			 e.printStackTrace();
		 } catch (DocumentException e) {
			 e.printStackTrace();
		 }
		 return Result.OK(null);
	 }

    /**
    * 导出excel
    *
    * @param request
    * @param invoiceInfo
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, InvoiceInfo invoiceInfo) {
        return super.exportXls(request, invoiceInfo, InvoiceInfo.class, "invoice_info");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, InvoiceInfo.class);
    }

}
